package org.example.cloudprviderpayment8001.aspect;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.cloudprviderpayment8001.annotion.DataSource;
import org.springframework.stereotype.Component;

import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;

@Aspect
@Component
public class DataSourceAspect {

    /*
    * @within和@target针对类的注解,@annotation是针对方法的注解,@args针对参数
    *
    * within(com.javacode…*)
    * */
    @Pointcut("@within(org.example.cloudprviderpayment8001.annotion.DataSource)")
    public void pointcut(){};

    @Before("pointcut()")
    public void doBefore(JoinPoint joinPoint){
        System.out.println("DataSource切面");
        Class<?> aClass = joinPoint.getTarget().getClass();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        methodMake(aClass,methodSignature);
    }

    public void methodMake(Class<?> aClass,MethodSignature methodSignature){
        if (aClass.isAnnotationPresent(DataSource.class)) {
            DataSource annotation = aClass.getAnnotation(DataSource.class);
            String value = annotation.value();
            DynamicDataSourceContextHolder.push(value);
        }else if (methodSignature.getMethod().isAnnotationPresent(DataSource.class)){
            DataSource annotation = methodSignature.getMethod().getAnnotation(DataSource.class);
            DynamicDataSourceContextHolder.push(annotation.value());
        }else {
            System.out.println("no method or class");
        }
    }

  /*  @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Class<? extends ProceedingJoinPoint> aClass = joinPoint.getClass();
        if (aClass.isAnnotationPresent(DataSource.class)){
            DataSource annotation = aClass.getAnnotation(DataSource.class);
            String value = annotation.value();
            System.out.println("数据源切换"+value);
        }
        System.out.println("环绕");
        return joinPoint.proceed();
    };*/
}
